<?php

function js($a) {
	global $config;

	if ($a[0] == '@') {
		$config['scripts'][] = $a;
	} else {
		$config['scripts']['_js'][] = $a;
	}
}

class JS {

	private static $_skip_dependencies = false;
	private static $_override_dependencies = null;

	public static function Add($code) {
		global $config;
		$config['scripts'][] = $code;
	}

	public static function AddOnLoad($code) {
		global $config;
		$config['scripts'][] = "$(function() {\n\t$code\n});";
	}

	public static function Load($file, $import = false) {
		global $config;
		if ($import) {
			$config['scripts'][$file] = file_get_contents($file);
		} else {
			$config['scripts'][$file] = "@$file";
		}
	}

	public static function OverrideDependencies() {
		if (func_num_args() == 0) {
			self::$_override_dependencies = null;
		} else {
			self::$_override_dependencies = func_get_args();
		}
	}

	/*
	 * IncludeDependencies()
	 * Should move dependancy declaration out of core??
	 */
	public static function IncludeDependencies() {
		global $config;

		if (!isset($config['scripts']) || !is_array($config['scripts'])) {
			$config['scripts'] = array();
		}

		if (!self::$_skip_dependencies) {
			if (isset(self::$_override_dependencies)) {
				$dependencies = self::$_override_dependencies;
			} else {
				$use_compressor = defined('YUI_COMPRESS_JS') && constant('YUI_COMPRESS_JS') && !(defined('YUI_COMPRESS_OVERRIDE') && constant('YUI_COMPRESS_OVERRIDE'));

				$yui_url = '';
				if (isset($config['static'])) {
					$url = '@' . $config['static']['url'];
					$jsCore = '@/js/core-min.js';
					$yui_url = $url . '/js/yui/build';
					$yui_base = $config['static']['path'] . '/js/yui/build';
				} else {
					$jsCore = '@/core.js';
					$yui_base = '/js/core/yui/build';
				}

				$dependencies = array($jsCore);
			}

			// want to be able to use this even if skip dependencies is enabled, but the logic for it is done inside the if block above
			if (isset($yui_base) && !defined('YUI_BASE')) {
				define('YUI_BASE', $yui_base);
			}

			if ($yui = YUI::Finalize()) {
				$yui_base_len = strlen($yui_base);
				$yui = array_reverse($yui);
				foreach ($yui as $module) {
					$module = $yui_url . substr($module, $yui_base_len);
					array_unshift($dependencies, $module);
				}
			}

			//array_unshift($config['scripts'], $jQuery , $jsCore);

			$dependencies = array_reverse($dependencies);
			foreach ($dependencies as $dependency) {
				array_unshift($config['scripts'], $dependency);
			}
		}
	}

	public static function SkipDependencies($val = true) {
		self::$_skip_dependencies = !!$val;
	}

}

class JSClosure {
	private $_parameters, $_code;

	public function __construct(array $parameters, $code) {
		$this->_parameters = $parameters;
		$this->_code = $code;
	}

	public function __toString() {
		return "function(".implode($this->_parameters,',').") {\n\t".$this->_code."\n\t}";
	}
}
